// Diego Garcia 11360
package calculadora;
import java.applet.*;
import java.awt.*;
public class Calculadora extends Applet{
        private Button b1= new Button("   =   ");
	private boolean ban = false;
	private TextField t1= new TextField(20);
	private Stack<String> memoria = new StackCircle();
	public void init()
	{
		add(t1);
		add(b1);
		setBackground(Color.GRAY);
		setSize(200, 100);
	}
    private double calc(){
        String t="";
        double a=0, b=0;
        if (!memoria.empty()){
            t=memoria.pop();             
            if (t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/")){
                b=calc();
                a=calc();
            }
            if (t.equals("*"))
                return a*b;
            else    if (t.equals("/"))
                        return a/b;
                    else    if (t.equals("-"))
                                return a-b;
                            else    if (t.equals("+"))
                                        return a+b;
                                    else{
                                        try{
                                            return Double.parseDouble(t);
                                        }
                                        catch(NumberFormatException nfe){
                                            ban = true;
                                            return 0;
                                        }
                                    }  
        }
        else{
        	ban = true;
        	return 0;
        }
        }
    public void paint(Graphics g)
	{
		if (ban){
			g.drawString("Error, ingreso no valido", 25, 75);
			t1.setText("");
		}
	}
	public boolean action(Event e, Object o)
	{
		String s="", tmp="";
		ban= false;
		if (e.target==b1){
			s=t1.getText()+" ";
	        for (int i=0; i<s.length(); i++)
	        {
	           if(s.charAt(i)!=' ') 
	            tmp=tmp+s.charAt(i);
	           else{
	               memoria.push(tmp);
	               tmp="";
	           }
	        }t1.setText(t1.getText()+" = "+calc());
		}
		repaint();
		return false;
	}
}
